#include "my_list.h"
#include "my_allocator.h"
#include <string.h>
#include "global_declarations.h"
#include "my_list.h"
#include <stdlib.h>

void insert_record_node(Node* node, unsigned int id, char* name);

/**
 * scans the list for the desired id
 */
Record* get_record_in_node(Node* node, unsigned int id) {
	int i;
	for (i = 0; i < node->occupied; ++i) {
		if (node->records[i].id == id)
			return &node->records[i];
	}
	return 0;
}

/**
 * creates a new list
 */
MyList* create_new_my_list() {
	MyList* p = malloc(sizeof(MyList));
	p->head = 0;
	return p;
}

/**
 * creates a new node.
 */
Node* create_new_node() {
	Node* p = malloc(sizeof(Node));
	memset(p, 0, sizeof(Node));
	return p;
}

/**
 * inserts a new record to the list.
 * if the head of the list is full, a new node is created.
 */
void insert_record_my_list(MyList* list, unsigned int id, char* name) {
	if (list->head == 0) {
		list->head = create_new_node();
		insert_record_node(list->head, id, name);
	} else if (list->head->occupied == ELEMENTS_PER_NODE) {
		Node* p = create_new_node();
		p->next = list->head;
		list->head = p;
		insert_record_node(p, id, name);
	} else {
		insert_record_node(list->head, id, name);
	}

}

/**
 * inserts a record to a node
 */
void insert_record_node(Node* node, unsigned int id, char* name) {
	char* name_copied;
	if (node->occupied < ELEMENTS_PER_NODE) {
		node->records[node->occupied].id = id;
		name_copied = my_allocate(get_allocator(), strlen(name) + 1);
		memcpy(name_copied, name, strlen(name) + 1);
		node->records[node->occupied].name = name_copied;
		node->occupied++;
	}
}

/**
 * looks for the record in the list.
 * if not found, return = 0.
 */
Record* retrieve_record_my_list(MyList* list, unsigned int id) {
	Record* rec;
	Node* p = list->head;
	while (p != 0) {
		rec = get_record_in_node(p, id);
		if (rec != 0) {
			return rec;
		} else {
			p = p->next;
		}
	}
	return 0;
}

/**
 * clears the list
 */
void clear_all_my_list(MyList* list) {
	Node* next, *cur;
	if (list != 0){
		cur = list->head;
		while(cur != 0){
			next = cur->next;
			free(cur);
			cur = next;
		}
		list->head = 0;
	}
}
